%Returns coeff of a polynomial that fits the curve in the picture
datadir = '.';
a = dir(datadir);
file = ['beam'];
PNGext = ['.png']   
fnamebild = [datadir filesep file PNGext];
figure(1);
[ima,map] = imread(fnamebild);
%axis([0 640 0 480])
high = size(ima,1);
width = size(ima,2);
imshow(fnamebild)
hold on
% Initially, the list of points is empty.
x = [];
y = [];
n = 0;
% Loop, picking up the points.
disp('Left mouse button picks points.')
disp('Right mouse button picks last point.')
but = 1;
while but == 1
    [xi,yi,but] = ginput(1);
    plot(xi,yi,'ro')
    n = n+1;
    x(n) = xi;
    y(n) = yi;
end

cs = spline(x,y);
xint = min(x):max(x);
% Interpolate with a spline and finer spacing.
beam = ppval(cs,xint);
% Plot the interpolated curve.
plot(xint,beam,'b-');
hold off

%Tangent at every point of the image.
tangent = diff(beam)./diff(xint);
tangent = [zeros(1,min(x)) tangent zeros(1,width - max(x))];
%length(tangent);
xplot = 1:length(tangent);
%Plot of the tangent
figure(2)
subplot(2,1,1)
plot(xplot,tangent,'r');title('Tangent at each pixel')
axis tight

%Plot the angle at each point
angle = atan(tangent);
subplot(2,1,2)
plot(xplot,angle,'g');title('Angle at each pixel')
axis tight


%files with data
save('angle')
save('tangent')
save('beam')
pause; close all;

%Print to a file
% open the file with write permission
fid = fopen('beam.txt', 'w');
fprintf(fid, '%f\n', beam);
fclose(fid);

fid = fopen('angle.txt', 'w');
fprintf(fid, '%f\n', angle);
fclose(fid);

fid = fopen('tangent.txt', 'w');
fprintf(fid, '%f\n', tangent);
fclose(fid);

% view the contents of the file
%type beam.txt



